// XMPP服务器BOSH地址
var BOSH_SERVICE = '';

// 房间JID
var ROOM_JID = '';

// XMPP连接
var connection = null;

// 当前状态是否连接
var connected = false;

// 当前登录的JID
var jid = "";

// 连接状态改变的事件
function roomOnConnect(status) {
    if (status == Strophe.Status.CONNFAIL) {
        console.log("连接失败！");
    } else if (status == Strophe.Status.AUTHFAIL) {
        console.log("登录失败！");
    } else if (status == Strophe.Status.DISCONNECTED) {
        console.log("连接断开！");
        connected = false;
    } else if (status == Strophe.Status.CONNECTED) {
        console.log("连接成功，可以开始聊天了！");
        connected = true;
        fun_closebox(); // 关闭加载

        // 当接收到<message>节，调用onMessage回调函数
        connection.addHandler(onMessage, null, 'message', null, null, null);

        // 首先要发送一个<presence>给服务器（initial presence）
        connection.send($pres().tree());

        // 发送<presence>元素，加入房间
        connection.send($pres({
            from: jid,
            to: ROOM_JID + "/" + jid.substring(0, jid.indexOf("@"))
        }).c('x', { xmlns: 'http://jabber.org/protocol/muc' }).tree());
    }
}

// 接收到<message>
function onMessage(msg) {
    //console.log(msg);
    // 解析出<message>的from、type属性，以及body子元素
    var from = msg.getAttribute('from');
    var type = msg.getAttribute('type');
    var elems = msg.getElementsByTagName('body');

    if (type == "groupchat" && elems.length > 0) {
        var body = elems[0];
        var uname = from.substring(from.indexOf('/') + 1);

        var faceurl = $("#iface_" + uname).attr('src');
        var nickname = $("#iname_" + uname).text();

        var msgline = "<li>";
        if (uname == jid.substring(0, jid.indexOf("@")))
            msgline = "<li class='current'>";
        msgline += "<div class='head'><img src='" + faceurl + "'/></div>";
        msgline += "<div class='name'>" + nickname + "</div>";
        msgline += "<div class='chat'>";
        msgline += "<div class='box'></div>";
        // 判断图片
        var msg_body = Strophe.getText(body);
        var imgurl = '';
        if (msg_body.indexOf('[img]') >= 0 && msg_body.indexOf('[/img]') >= 0) {
            msg_body = msg_body.replace('[img]', '');
            msg_body = msg_body.replace('[/img]', '');
            imgurl = msg_body;
            msg_body = '<img src="' + imgurl + '" alt=""/>';
        } else {
            fun_closebox(); // 关闭加载
        }
        msgline += msg_body;
        msgline += "</div>";
        msgline += "<div class='clear'></div>";
        msgline += "</li>";

        loadImage(imgurl);

        $('#chatlist').append(msgline);
        chat_bottom();

        $("#chatlist li .chat img").click(function () {
            var bodyheight = $("body").height();

            var oldwidth = $(this).width();
            $(this).width('10rem');
            var curheight = $(this).height();
            $(this).width(oldwidth);
            var market_html = "";
            if (curheight > bodyheight)
                market_html += "<div class='market_box' onclick='fun_closebox()' style='height:" + bodyheight + "px;overflow-y:scroll;'>";
            else
                market_html += "<div class='market_box' onclick='fun_closebox()' style='height:" + bodyheight + "px'>";
            //market_html += "<div class='cashtit'><div class='close' onclick='fun_closebox();'><img src='../images/close.png' /></div></div>";
            market_html += "<div><img src='" + $(this).attr("src") + "'/></div>";
            market_html += "</div>";

            layer.open({
                type: 1,
                title:'',
                content: market_html,
                anim: 'up',
                style: 'position:fixed;background:transparent;top:0;left:50%;width:10rem;margin-left:-5rem;border: none; -webkit-animation-duration: .5s; animation-duration: .5s;'
            });
        });
    }
    return true;
}

function loadImage(url) {
    var img = new Image(); //创建一个Image对象，实现图片的预下载    
    img.onload = function () {
        img.onload = null;
        console.log('加载完毕：' + url);
        chat_bottom();
        fun_closebox(); // 关闭加载
    }
    img.src = url;
}


// 房间聊天连接
function loginRoom(t_jid,pwd) {
    if (!connected) {
        console.log('登录...');
        layer.open({ type: 2, shade: false });  // load 加载
        connection = new Strophe.Connection(BOSH_SERVICE);
        connection.connect(t_jid, pwd, roomOnConnect);
        jid = t_jid;
    }
}

function sendChat(msg) {
    layer.open({ type: 2, shade: false });  // load 加载
    if (connected) {
        // 创建一个<message>元素并发送
        var msg = $msg({
            to: ROOM_JID,
            from: jid,
            type: 'groupchat'
        }).c("body", null, msg);
        //console.log(msg);
        connection.send(msg.tree());
        $("#txtmsg").val('');
    } else {
        console.log('连接断开重新登录...');
        loginRoom(current_name, current_pwd);
    }
}

// 回到聊天底部
function chat_bottom() {
    var chat = document.getElementById("chatlist");
    chat.scrollTop = chat.scrollHeight;
}
/***关闭弹出层***/
function fun_closebox() {
    layer.closeAll();
};